import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild,
  CanLoad, Route
} from '@angular/router';
import { LoginInOutService } from '@core/services/common/login-in-out.service';
import { AuthService } from '@core/services/common/auth.service';

@Injectable({
  providedIn: 'root',
})
export class LoginRouterGuard implements CanActivate, CanActivateChild, CanLoad {

  constructor(
    private loginInOutService: LoginInOutService,
    private router: Router,
    private auth: AuthService
  ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    //console.logR('canActivate', route, state);
    const url: string = state.url;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    //console.logR('canActivateChild', route, state);
    return this.canActivate(route, state);
  }

  canLoad(route: Route): boolean {
    const url = `/${route.path}`;
    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    const authToken: string = this.auth.getAuthorizationToken();
    if (authToken) {
      if (url === '/login') {
        this.router.navigate(['/home']);
      }
    } else {
      console.log('没有登录授权,跳转回登录页面,并重置登录权限！');
      if (url === '/login') {
        this.loginInOutService.logout();
      } else {
        this.router.navigate(['/login']);
        return false;
      }
    }
    return true;
  }
}
